/*!
 * Copyright (C) 2020 - All Rights Reserved by
 * @author : ZhaoYanbo
 * @email  : zyb920@hotmail.com
 * @created: 2020-10-31
 * @version: 1.0.0.0
 *
 */

#include "ListDelegate.h"
#include "ListModel.h"
#include <QPainter>
#include <QtDebug>
#include <QListView>
#include <QMouseEvent>

ListDelegate::ListDelegate(QObject *parent) : QStyledItemDelegate(parent)
{

}

QWidget *ListDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    Q_UNUSED(parent)
    Q_UNUSED(option)
    Q_UNUSED(index)

    return  nullptr;
}

void ListDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QStyledItemDelegate::paint(painter, option, index);
    if (index.isValid())
    {
        const QString txt = index.data(ListModel::NameRole).toString();

        painter->save();
        painter->setPen(Qt::white);
        painter->setFont(option.font);

        if(index.data(ListModel::HeadRole).toBool()) //可以单独在此绘制
        {
            bool b = index.data(ListModel::ExpandRole).toBool();
            if(b)
                painter->drawText(option.rect, Qt::AlignVCenter, "-");
            else
                painter->drawText(option.rect, Qt::AlignVCenter, "+");

            painter->drawText(option.rect.adjusted(20,0,0,0), Qt::AlignVCenter, txt);
        }
        else
            painter->drawText(option.rect, Qt::AlignCenter, txt);

        painter->restore();
    }
}

QSize ListDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    (void) option;
    QListView *view = dynamic_cast<QListView *>(index.model()->parent());
    if(view) {
        if(index.data(ListModel::HeadRole).toBool()) //如果是section
            return QSize(view->viewport()->width(), 40);
    }

    return QSize(60, 60);
}

bool ListDelegate::editorEvent(QEvent *event, QAbstractItemModel *model,
                               const QStyleOptionViewItem &option, const QModelIndex &index)
{
    switch (event->type())
    {
    case QEvent::MouseButtonPress:
    {
        //QMouseEvent* e = dynamic_cast<QMouseEvent*>(event);
        if(index.data(ListModel::HeadRole).toBool()) //可以单独在此绘制
        {
            bool b = index.data(ListModel::ExpandRole).toBool();
            model->setData(index, !b, ListModel::ExpandRole);
        }
        break;
    }
    default: break;
    }
    return QStyledItemDelegate::editorEvent(event, model, option, index);
}
